<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入文章标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="所属部门" prop="dept">
        <treeselect style="width: 240px" v-model="queryParams.dept" :options="deptOptions" :show-count="true" placeholder="请选择所属部门" clearable />
      </el-form-item>
      <el-form-item label="一级分类" prop="articleOneClass">
        <el-select v-model="queryParams.articleOneClass" placeholder="请选择一级分类" clearable @change="handleOneClassChange">
          <el-option
            v-for="menu in retirementMenuList"
            :key="menu.id"
            :label="menu.name"
            :value="menu.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类" prop="articleTwoClass">
        <el-select v-model="queryParams.articleTwoClass" placeholder="请选择二级分类" clearable>
          <el-option
            v-for="classTwo in retirementClassTwoList"
            :key="classTwo.id"
            :label="classTwo.name"
            :value="classTwo.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文章类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择文章类型" clearable @change="handleQueryTypeChange">
          <el-option
            v-for="dict in dict.type.article_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文章状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择文章状态" clearable>
          <el-option
            v-for="dict in dict.type.article_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['retirement:retirementArticle:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single || !isSelectedArticlesOperable"
          @click="handleUpdate"
          v-hasPermi="['retirement:retirementArticle:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple || !isSelectedArticlesOperable"
          @click="handleDelete"
          v-hasPermi="['retirement:retirementArticle:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['retirement:retirementArticle:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="table" v-loading="loading" :data="retirementArticleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键" align="center" prop="id" />-->
      <el-table-column label="文章标题" align="center" prop="title">
      <template slot-scope="scope">
        <div class="text-truncate" :title="scope.row.title" @click="showContentDialog('文章标题', scope.row.title)">
          {{ scope.row.title }}
        </div>
      </template>
      </el-table-column>>
<!--      <el-table-column label="文章内容富文本" align="center" prop="desc" />-->
      <el-table-column label="所属部门" align="center" prop="deptName" />
      <el-table-column label="所属一级分类" align="center" prop="articleOneClassName" />
      <el-table-column label="所属二级分类" align="center" prop="articleTwoClassName" />
      <el-table-column label="文章类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.article_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="文章封面图" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="是否置顶" align="center" prop="isTop" >
        <template slot-scope="scope">
          <span>{{ scope.row.isTop === '1' ? '是' : '否' }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="文号" align="center" prop="policyCode" />
      <el-table-column label="发文地址" align="center" prop="location" />
      <el-table-column label="发文机构" align="center" prop="source" />-->
      <!--   0草稿 1审核中 2驳回 3已发布    -->
      <el-table-column label="文章状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.article_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="发布时间" align="center" prop="date" />
      <el-table-column label="驳回原因" align="center" prop="reason" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            :disabled="scope.row.status === '1' || scope.row.status === '3'"
            v-hasPermi="['retirement:retirementArticle:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            :disabled="scope.row.status === '1' || scope.row.status === '3'"
            v-hasPermi="['retirement:retirementArticle:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文章发布对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="45%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 基本信息区域 - 两列布局 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入文章标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="dept">
              <treeselect v-model="form.dept" :options="deptOptions" :show-count="true" placeholder="请选择所属部门" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="一级分类" prop="articleOneClass">
              <el-select v-model="form.articleOneClass" placeholder="请选择一级分类" style="width: 100%" @change="handleFormOneClassChange">
                <el-option
                  v-for="menu in retirementMenuList"
                  :key="menu.id"
                  :label="menu.name"
                  :value="menu.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级分类" prop="articleTwoClass">
              <el-select v-model="form.articleTwoClass" placeholder="请选择二级分类" style="width: 100%">
                <el-option
                  v-for="classTwo in formClassTwoList"
                  :key="classTwo.id"
                  :label="classTwo.name"
                  :value="classTwo.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文章类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择文章类型" style="width: 100%" @change="handleFormTypeChange">
                <el-option
                  v-for="dict in dict.type.article_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否置顶" prop="isTop">
              <el-select v-model="form.isTop" placeholder="请选择是否置顶" style="width: 100%">
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="shouldShowPolicyCode">
          <el-col :span="12">
            <el-form-item label="文号" prop="policyCode">
              <el-input v-model="form.policyCode" placeholder="请输入文号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发文机构" prop="source">
              <el-input v-model="form.source" placeholder="请输入发文机构" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="shouldShowLocation">
          <el-col :span="12">
            <el-form-item label="活动地址" prop="location">
              <el-input v-model="form.location" placeholder="请输入活动地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="deadline">
              <el-date-picker
                v-model="form.deadline"
                type="datetime"
                placeholder="请选择截止时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
                @change="handleDeadlineChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文章封面图" prop="image">
              <image-upload v-model="form.image" :limit="1"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 富文本编辑器区域 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="文章内容" prop="desc">
              <div id="editor" style="border: 1px solid #dcdfe6; border-radius: 4px;"></div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveAsDraft">草 稿</el-button>
        <el-button type="primary" @click="submitForm">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 内容展示弹框 -->
    <el-dialog :title="contentDialog.title" :visible.sync="contentDialog.visible" width="60%" append-to-body>
      <div class="content-display">
        <pre>{{ contentDialog.content }}</pre>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="contentDialog.visible = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listRetirementArticle, getRetirementArticle, delRetirementArticle, addRetirementArticle, updateRetirementArticle } from "@/api/retirement/retirementArticle"
import { listRetirementMenu } from "@/api/retirement/retirementMenu"
import { listRetirementClassTwo } from "@/api/retirement/retirementClassTwo"
import { deptTreeSelect } from "@/api/system/user"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import E from "wangeditor"
import hljs from "highlight.js"
import { getToken } from "@/utils/auth"

export default {
  name: "RetirementArticle",
  components: { Treeselect },
  dicts: ['article_type', 'article_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文章发布表格数据
      retirementArticleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门树选项
      deptOptions: [],
      // 一级分类列表数据
      retirementMenuList: [],
      // 二级分类列表数据（用于搜索）
      retirementClassTwoList: [],
      // 二级分类列表数据（用于表单）
      formClassTwoList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        desc: null,
        dept: null,
        articleOneClass: null,
        articleTwoClass: null,
        type: null,
        policyCode: null,
        image: null,
        isTop: null,
        location: null,
        source: null,
        status: null,
        reason: null,
        date: null,
        isDel: null,
      },
      // 内容展示弹框
      contentDialog: {
        visible: false,
        title: '',
        content: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "文章标题不能为空", trigger: "blur" }
        ],
        dept: [
          { required: true, message: "所属部门不能为空", trigger: "change" }
        ],
        articleOneClass: [
          { required: true, message: "一级分类不能为空", trigger: "change" }
        ],
        articleTwoClass: [
          { required: true, message: "二级分类不能为空", trigger: "change" }
        ],
        type: [
          { required: true, message: "文章类型不能为空", trigger: "change" }
        ],
        isTop: [
          { required: true, message: "是否置顶不能为空", trigger: "change" }
        ],
        image: [
          { required: true, message: "文章封面图不能为空", trigger: "change" }
        ],
        desc: [
          { required: true, message: "文章内容不能为空", trigger: "blur" }
        ],
        policyCode: [
          {
            validator: (rule, value, callback) => {
              if (this.shouldShowPolicyCode && (!value || value.trim() === '')) {
                callback(new Error('文号不能为空'))
              } else {
                callback()
              }
            },
            trigger: "blur"
          }
        ],
        source: [
          {
            validator: (rule, value, callback) => {
              if (this.shouldShowPolicyCode && (!value || value.trim() === '')) {
                callback(new Error('发文机构不能为空'))
              } else {
                callback()
              }
            },
            trigger: "blur"
          }
        ],
        location: [
          {
            validator: (rule, value, callback) => {
              if (this.shouldShowLocation && (!value || value.trim() === '')) {
                callback(new Error('发文地址不能为空'))
              } else {
                callback()
              }
            },
            trigger: "blur"
          }
        ],
        deadline: [
          {
            validator: (rule, value, callback) => {
              if (this.shouldShowLocation && (!value || value.trim() === '')) {
                callback(new Error('截止时间不能为空'))
              } else {
                callback()
              }
            },
            trigger: "change"
          }
        ]
      },
      editor:null,
    }
  },
  computed: {
    /** 是否显示文号和发文机构（政策类型时显示） */
    shouldShowPolicyCode() {
      return this.form.type === 'policy'
    },
    /** 是否显示发文地址（活动类型时显示） */
    shouldShowLocation() {
      return this.form.type === 'activity'
    },
    /** 选中的文章是否都可操作 */
    isSelectedArticlesOperable() {
      if (this.ids.length === 0) return false
      const selectedArticles = this.retirementArticleList.filter(article => this.ids.includes(article.id))
      return selectedArticles.every(article => this.isArticleOperable(article.status))
    }
  },
  created() {
    this.getList()
    this.getDeptTree()
    this.getRetirementMenuList()
    this.getRetirementClassTwoList()
  },
  mounted() {
    // 编辑器将在对话框打开时初始化
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy()
    }
  },
  methods: {
    /** 检查文章状态是否可操作（状态为1审核中或2审核通过时不可操作） */
    isArticleOperable(status) {
      return status !== '1' && status !== '3'
    },

    /** 初始化富文本编辑器 */
    initEditor() {
      this.$nextTick(() => {
        // 如果编辑器已存在，先销毁
        if (this.editor) {
          this.editor.destroy()
          this.editor = null
        }
        this.editor = new E('#editor')
        // 配置编辑器
        this.editor.config.height = 300
        this.editor.config.zIndex = 1
        this.editor.config.placeholder = '请输入文章内容...'

        // 配置图片上传
        this.editor.config.uploadImgServer = process.env.VUE_APP_BASE_API + '/common/editor/upload'
        this.editor.config.uploadFileName = 'file'
        this.editor.config.uploadImgParams = {
          // 上传参数
          type:"img"
        }
        this.editor.config.uploadImgHeaders = {
          Authorization: "Bearer " + getToken()
        }
        // 限制图片上传数量为1张
        this.editor.config.uploadImgMaxLength = 1
        this.editor.config.uploadImgHooks = {
          // 上传前验证
          before: (xhr, editor, files) => {
            // 检查文件数量
            if (files.length > 1) {
              this.$modal.msgError('一次只能上传一张图片')
              return false
            }
            // 检查文件大小（5MB = 5 * 1024 * 1024 bytes）
            const file = files[0]
            const maxSize = 5 * 1024 * 1024
            if (file.size > maxSize) {
              this.$modal.msgError('图片大小不能超过5MB')
              return false
            }
            // 检查文件类型
            const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
            if (!allowedTypes.includes(file.type)) {
              this.$modal.msgError('只支持上传 JPG、PNG、GIF、WebP 格式的图片')
              return false
            }
            this.$modal.loading("正在上传图片，请稍候...")
            return true
          },
          // 上传成功后的回调
          success: (xhr, editor, result) => {
            console.log('图片上传成功', result)
            this.$modal.closeLoading()
          },
          // 上传失败的回调
          fail: (xhr, editor, result) => {
            console.log('图片上传失败', result)
            this.$modal.closeLoading()
            this.$modal.msgError('图片上传失败：' + (result.msg || '未知错误'))
            return false
          },
          // 上传错误
          error: (xhr, editor) => {
            console.log('图片上传出错')
            this.$modal.closeLoading()
            this.$modal.msgError('图片上传出错')
            return false
          },
          // 上传超时
          timeout: (xhr, editor) => {
            console.log('图片上传超时')
            this.$modal.closeLoading()
            this.$modal.msgError('图片上传超时')
            return false
          }
        }
        // 配置视频上传
        this.editor.config.uploadVideoServer = process.env.VUE_APP_BASE_API + '/common/editor/upload'
        this.editor.config.uploadVideoName = 'file'
        this.editor.config.uploadVideoParams = {
          // 视频上传参数
          type:"video"
        }
        this.editor.config.uploadVideoHeaders = {
          Authorization: "Bearer " + getToken()
        }
        this.editor.config.uploadVideoHooks = {
          success: (xhr, editor, result) => {
            console.log('视频上传成功', result)
            this.$modal.closeLoading()
          },
          fail: (xhr, editor, result) => {
            console.log('视频上传失败', result)
            this.$modal.closeLoading()
            this.$modal.msgError('视频上传失败')
          },
          error: (xhr, editor) => {
            console.log('视频上传出错')
            this.$modal.closeLoading()
            this.$modal.msgError('视频上传出错')
          },
          timeout: (xhr, editor) => {
            console.log('视频上传超时')
            this.$modal.closeLoading()
            this.$modal.msgError('视频上传超时')
          },
          before: (xhr, editor, files) => {
            this.$modal.loading("正在上传视频，请稍候...")
          }
        }
        // 创建编辑器
        this.editor.create()
        // 监听内容变化
        this.editor.config.onchange = (html) => {
          this.form.desc = html
        }
      })
    },
    /** 查询文章发布列表 */
    getList() {
      this.loading = true
      listRetirementArticle(this.queryParams).then(response => {
        this.retirementArticleList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
      // 销毁编辑器
      if (this.editor) {
        this.editor.destroy()
        this.editor = null
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        desc: null,
        dept: null,
        deptId: null,
        articleOneClass: null,
        articleTwoClass: null,
        type: null,
        policyCode: null,
        image: null,
        isTop: null,
        location: null,
        source: null,
        status: null,
        reason: null,
        date: null,
        isDel: null,
        deadline: null,
        deadlineStr: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      // 重置时重新获取所有二级分类
      this.getRetirementClassTwoList()
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加文章发布"
      // 初始化编辑器
      this.$nextTick(() => {
        this.initEditor()
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // 如果是单个修改，检查文章状态
      if (row && row.id) {
        if (!this.isArticleOperable(row.status)) {
          this.$modal.msgError("该文章状态为审核中或审核通过，不可修改！")
          return
        }
      } else if (this.ids.length > 0) {
        // 批量修改只允许选择一条数据
        if (this.ids.length !== 1) {
          this.$modal.msgError("修改操作只能选择一条数据！")
          return
        }
        // 检查选中的文章状态
        const selectedArticle = this.retirementArticleList.find(article => this.ids.includes(article.id))
        if (selectedArticle && !this.isArticleOperable(selectedArticle.status)) {
          this.$modal.msgError("该文章状态为审核中或审核通过，不可修改！")
          return
        }
      }

      this.reset()
      const id = row ? row.id : this.ids[0]
      getRetirementArticle(id).then(response => {
        this.form = response.data
        // 确保isTop字段为数字类型，以便正确回显
        if (this.form.isTop !== null && this.form.isTop !== undefined) {
          this.form.isTop = parseInt(this.form.isTop)
        }
        this.open = true
        this.title = "修改文章发布"
        // 如果有一级分类，加载对应的二级分类
        if (this.form.articleOneClass) {
          this.getFormClassTwoList(this.form.articleOneClass)
        }
        // 初始化编辑器并设置内容
        this.$nextTick(() => {
          this.initEditor()
          // 延迟设置内容，确保编辑器已创建
          setTimeout(() => {
            if (this.editor && this.form.desc) {
              this.editor.txt.html(this.form.desc)
            }
          }, 100)
        })
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 显示全局loading，防止重复提交
          this.$modal.loading("正在提交，请稍候...")

          // 获取富文本内容
          if (this.editor) {
            this.form.desc = this.editor.txt.html()
          }

          // 设置状态为提交
          this.form.status = 1
          console.info(this.form.deadlineStr)
          if (this.form.id != null) {
            updateRetirementArticle(this.form).then(response => {
              this.$modal.closeLoading()
              this.$modal.msgSuccess("提交成功")
              this.open = false
              this.getList()
              // 销毁编辑器
              if (this.editor) {
                this.editor.destroy()
                this.editor = null
              }
            }).catch(error => {
              this.$modal.closeLoading()
              console.error('提交失败:', error)
            })
          } else {
            addRetirementArticle(this.form).then(response => {
              this.$modal.closeLoading()
              this.$modal.msgSuccess("提交成功")
              this.open = false
              this.getList()
              // 销毁编辑器
              if (this.editor) {
                this.editor.destroy()
                this.editor = null
              }
            }).catch(error => {
              this.$modal.closeLoading()
              console.error('提交失败:', error)
            })
          }
        }
      })
    },
    /** 保存草稿按钮 */
    saveAsDraft() {
      // 显示全局loading，防止重复提交
      this.$modal.loading("正在保存草稿，请稍候...")

      // 获取富文本内容
      if (this.editor) {
        this.form.desc = this.editor.txt.html()
      }

      // 设置状态为草稿
      this.form.status = 0

      if (this.form.id != null) {
        updateRetirementArticle(this.form).then(response => {
          this.$modal.closeLoading()
          this.$modal.msgSuccess("保存草稿成功")
          this.open = false
          this.getList()
          // 销毁编辑器
          if (this.editor) {
            this.editor.destroy()
            this.editor = null
          }
        }).catch(error => {
          this.$modal.closeLoading()
          console.error('保存草稿失败:', error)
        })
      } else {
        addRetirementArticle(this.form).then(response => {
          this.$modal.closeLoading()
          this.$modal.msgSuccess("保存草稿成功")
          this.open = false
          this.getList()
          // 销毁编辑器
          if (this.editor) {
            this.editor.destroy()
            this.editor = null
          }
        }).catch(error => {
          this.$modal.closeLoading()
          console.error('保存草稿失败:', error)
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // 如果是单个删除，检查文章状态
      if (row && row.id) {
        if (!this.isArticleOperable(row.status)) {
          this.$modal.msgError("该文章状态为审核中或审核通过，不可删除！")
          return
        }
      }

      // 如果是批量删除，检查选中的文章状态
      if (!row && this.ids.length > 0) {
        const selectedArticles = this.retirementArticleList.filter(article => this.ids.includes(article.id))
        const inoperableArticles = selectedArticles.filter(article => !this.isArticleOperable(article.status))
        if (inoperableArticles.length > 0) {
          this.$modal.msgError("有不可操作的数据，请重新选择！")
          return
        }
      }

      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除文章发布编号为"' + ids + '"的数据项？').then(function() {
        return delRetirementArticle(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('retirement/retirementArticle/export', {
        ...this.queryParams
      }, `retirementArticle_${new Date().getTime()}.xlsx`)
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    /** 获取一级分类列表 */
    getRetirementMenuList() {
      listRetirementMenu({}).then(response => {
        this.retirementMenuList = response.data || []
      })
    },
    /** 获取二级分类列表（用于搜索） */
    getRetirementClassTwoList() {
      listRetirementClassTwo({}).then(response => {
        this.retirementClassTwoList = response.data || []
      })
    },
    /** 根据一级分类ID获取二级分类列表（用于表单） */
    getFormClassTwoList(levelOneId) {
      if (!levelOneId) {
        this.formClassTwoList = []
        return
      }
      listRetirementClassTwo({ levelOneId: levelOneId }).then(response => {
        this.formClassTwoList = response.data || []
      })
    },
    /** 根据一级分类ID获取二级分类列表（用于搜索） */
    getQueryClassTwoList(levelOneId) {
      if (!levelOneId) {
        this.retirementClassTwoList = []
        return
      }
      listRetirementClassTwo({ levelOneId: levelOneId }).then(response => {
        this.retirementClassTwoList = response.data || []
      })
    },
    /** 搜索表单一级分类变化处理 */
    handleOneClassChange(value) {
      // 清空二级分类选择
      this.queryParams.articleTwoClass = null
      // 根据一级分类ID获取对应的二级分类
      this.getQueryClassTwoList(value)
    },
    /** 编辑表单一级分类变化处理 */
    handleFormOneClassChange(value) {
      // 清空二级分类选择
      this.form.articleTwoClass = null
      // 根据一级分类ID获取对应的二级分类
      this.getFormClassTwoList(value)
    },
    /** 搜索表单文章类型变化处理 */
    handleQueryTypeChange(value) {
      // 这里可以添加搜索表单文章类型变化的逻辑
      console.log('搜索表单文章类型变化:', value)
    },
    /** 编辑表单文章类型变化处理 */
    handleFormTypeChange(value) {
      // 根据文章类型清空相关字段
      if (value === '1' || value === 1) {
        // 文章类型：隐藏文号、发文地址、发文机构
        this.form.policyCode = null
        this.form.location = null
        this.form.source = null
        this.form.deadline = null
        this.form.deadlineStr = null
      } else if (value === '2' || value === 2) {
        // 活动类型：隐藏文号、发文机构，显示发文地址
        this.form.policyCode = null
        this.form.source = null
      } else if (value === '3' || value === 3) {
        // 政策类型：隐藏发文地址，显示文号、发文机构
        this.form.location = null
        this.form.deadline = null
        this.form.deadlineStr = null
      }
      console.log('编辑表单文章类型变化:', value)
    },
    /** 截止时间变化处理 */
    handleDeadlineChange(value) {
      if (value) {
        // 将日期时间字符串转换为时间戳
        this.form.deadlineStr = new Date(value).getTime()/1000
      } else {
        this.form.deadlineStr = null
      }
    },
    // 显示内容弹框
    showContentDialog(title, content) {
      this.contentDialog.title = title
      this.contentDialog.content = content
      this.contentDialog.visible = true
    },
  }
}
</script>

<style scoped>
.text-truncate {
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
  color: #409EFF;
}

.text-truncate:hover {
  color: #66b1ff;
}

.content-display {
  max-height: 500px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.content-display pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  font-family: inherit;
  line-height: 1.5;
}
</style>
